import { useEffect, useState } from 'react'
import { Button, Card, Checkbox, Drawer, Form, Input, message, Modal, Radio, Select, Space } from 'antd'

import { selectFilterOption } from '@/utils/utils'
import { getStatusGroupName } from '@oBiz/components/EventSelect/utils'
import { apiAddEventTemplate, apiGetEventTemplateDetail, apiUpdateEventTemplate } from '../apis'
import { IAddEventTemplateReq, IEventTemplateODTO, IUpdateEventTemplateReq } from '../interface'
import {
  getEnableFlagName,
  getFirstLineName,
  getLocationTypeName,
  getMessageTypeName,
  getShipTrackStatusName,
  getStatusListOption,
  getTailLineName,
  getVisibleFlagName,
  popupSlot,
} from '../utils'
import { TFormValues } from './interface'
import styles from './style.module.less'

const updatePopup = popupSlot.insert(null)

interface IAddOrEditEventTemplateDrawerProps {
  /** 有值则视为编辑 */
  eventTemplateId: IEventTemplateODTO['eventTemplateId']
  /** 新增或编辑成功回调 */
  onSuccess?: () => void
}

export const AddOrEditEventTemplateDrawer = Object.assign(
  ({ eventTemplateId, onSuccess, destroy }: IAddOrEditEventTemplateDrawerProps & { destroy: () => void }) => {
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)
    const [form] = Form.useForm<TFormValues>()
    const [fetching, setFetching] = useState(false)
    const [submitting, setSubmitting] = useState(false)
    const actionName = eventTemplateId ? '更新' : '保存'

    const onValuesChange = (changedValues: TFormValues, allValues: TFormValues) => {
      if (changedValues.statusGroup) {
        form.setFieldValue('status', undefined)
      }
    }

    // 统一提交函数（运行时分发到对应 API）
    const mutateEventTemplate = (req: IUpdateEventTemplateReq | IAddEventTemplateReq) => {
      return 'eventTemplateId' in req ? apiUpdateEventTemplate(req) : apiAddEventTemplate(req)
    }

    useEffect(() => {
      if (eventTemplateId) {
        setFetching(true)
        apiGetEventTemplateDetail({ eventTemplateId })
          .then(res => {
            form.setFieldsValue(res)
          })
          .finally(() => setFetching(false))
      }
    }, [eventTemplateId])

    useEffect(() => () => form.resetFields(), [])

    return (
      <Drawer
        styles={{ header: { backgroundColor: 'var(--fba-bg)' }, body: { backgroundColor: 'var(--fba-bg)' } }}
        title={`${eventTemplateId ? '编辑' : '新增'}事件模板`}
        width={600}
        open={open}
        onClose={onHide}
        loading={fetching}
        afterOpenChange={afterOpenChange}
        footer={
          <div className={styles.footer}>
            <Space>
              <Button onClick={onHide}>取消</Button>
              <Button
                type="primary"
                disabled={fetching}
                loading={submitting}
                onClick={async () => {
                  form.submit() // 触发 scrollToFirstError
                  let values = await form.validateFields()
                  values = form.getFieldsValue(true)
                  Modal.confirm({
                    title: `确认要${actionName}吗？`,
                    onOk: async () => {
                      setSubmitting(true)
                      try {
                        const req = eventTemplateId ? { ...values, eventTemplateId } : values
                        await mutateEventTemplate(req)
                        message.success(`${actionName}成功`)
                        onSuccess?.()
                        onHide()
                      } finally {
                        setSubmitting(false)
                      }
                    },
                  })
                }}
              >
                {actionName}
              </Button>
            </Space>
          </div>
        }
      >
        <Card>
          <Form form={form} layout="vertical" onValuesChange={onValuesChange}>
            <Form.Item name="templateCn" label="中文描述" rules={[{ required: true, message: '请输入中文描述' }]}>
              <Input placeholder="请输入中文描述" />
            </Form.Item>
            <Form.Item name="templateEn" label="英文描述" rules={[{ required: true, message: '请输入英文描述' }]}>
              <Input placeholder="请输入英文描述" />
            </Form.Item>
            <Form.Item name="timestampDescription" label="时间戳说明">
              <Input placeholder="请输入时间戳说明" />
            </Form.Item>
            <Form.Item
              name="statusCode"
              label="Event Status"
              rules={[
                { required: true, pattern: /^[A-Z0-9]{2}$/, message: '请输入2个字符，仅支持大写英文字母和数字，如:CR' },
              ]}
            >
              <Input placeholder="请输入2个字符，如:CR" />
            </Form.Item>
            <Form.Item
              name="reasonCode"
              label="Event Reason"
              rules={[
                { required: true, pattern: /^[A-Z0-9]{2}$/, message: '请输入2个字符，仅支持大写英文字母和数字，如:EA' },
              ]}
            >
              <Input placeholder="请输入2个字符，如:EA" />
            </Form.Item>
            <Form.Item
              name="shipTrackRequire"
              label="ShipTrack要求"
              rules={[{ required: true, message: '请选择ShipTrack要求' }]}
            >
              <Radio.Group
                options={getShipTrackStatusName.valueList.map(d => ({ label: getShipTrackStatusName(d), value: d }))}
              />
            </Form.Item>
            <Form.Item name="messageType" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
              <Radio.Group
                options={getMessageTypeName.valueList.map(d => ({ label: getMessageTypeName(d), value: d }))}
              />
            </Form.Item>
            <Form.Item name="statusGroup" label="对应状态组" rules={[{ required: true, message: '请选择对应状态组' }]}>
              <Select
                allowClear
                placeholder="请选择对应状态组"
                options={getStatusGroupName.valueList.map(d => ({ label: getStatusGroupName(d), value: d }))}
                filterOption={selectFilterOption}
              />
            </Form.Item>
            <Form.Item noStyle shouldUpdate={(cur, prev) => cur.statusGroup !== prev.statusGroup}>
              {({ getFieldValue }) => {
                const statusGroup = getFieldValue('statusGroup') as 1 | 2 | 3 | 4 | 5 | 6
                const option = statusGroup ? getStatusListOption[statusGroup] : []
                return (
                  <Form.Item name="status" label="对应状态" rules={[{ required: true, message: '请选择对应状态' }]}>
                    <Select
                      allowClear
                      placeholder="请选择对应状态"
                      options={option}
                      filterOption={selectFilterOption}
                    />
                  </Form.Item>
                )
              }}
            </Form.Item>
            <Form.Item
              name="firstLines"
              label="适用头程运输方式"
              rules={[{ required: true, message: '请选择适用头程运输方式' }]}
            >
              <Checkbox.Group
                options={getFirstLineName.valueList.map(d => ({ label: getFirstLineName(d), value: d }))}
              />
            </Form.Item>
            <Form.Item
              name="tailLines"
              label="适用尾程运输方式"
              rules={[{ required: true, message: '请选择适用尾程运输方式' }]}
            >
              <Checkbox.Group options={getTailLineName.valueList.map(d => ({ label: getTailLineName(d), value: d }))} />
            </Form.Item>
            <Form.Item
              name="locationType"
              label="适用位置类型"
              rules={[{ required: true, message: '请选择适用位置类型' }]}
            >
              <Select
                allowClear
                placeholder="请选择适用位置类型"
                options={getLocationTypeName.valueList.map(d => ({ label: getLocationTypeName(d), value: d }))}
                filterOption={selectFilterOption}
              />
            </Form.Item>
            <Form.Item
              name="visibleFlag"
              label="客户可见"
              rules={[{ required: true, message: '请选择客户可见' }]}
              initialValue={1}
            >
              <Radio.Group
                options={getVisibleFlagName.valueList.map(d => ({ label: getVisibleFlagName(d), value: d }))}
              />
            </Form.Item>
            <Form.Item
              name="enableFlag"
              label="启用状态"
              rules={[{ required: true, message: '请选择启用状态' }]}
              initialValue={1}
            >
              <Radio.Group
                options={getEnableFlagName.valueList.map(d => ({ label: getEnableFlagName(d), value: d }))}
              />
            </Form.Item>
          </Form>
        </Card>
      </Drawer>
    )
  },
  {
    open: (props: IAddOrEditEventTemplateDrawerProps) => {
      updatePopup(<AddOrEditEventTemplateDrawer {...props} destroy={() => updatePopup(null)} />)
    },
  },
)
